package cc.geguol.transaction;

import org.junit.Test;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * 作者  Administrator
 * 时间  2017/2/14 9:23
 * 文件  JDBCDemo
 * 描述  事务
 */
public class TransactionDemo {
	private String url = "jdbc:mysql://localhost:3306/demo";
	private String user = "root";
	private String password = "root";

	@Test
	public void test2() throws ClassNotFoundException, SQLException {
		Class.forName("com.mysql.jdbc.Driver");
		Connection conn = DriverManager.getConnection(url, user, password);
//		Statement cs = conn.createStatement();
		String sql = "INSERT INTO student(name,gender) VALUES (?,?)";
//		String sql1 = "INSERT INTO student(name,gender) VALUES ('geguo','男')";
		conn.setAutoCommit(false);
		try {
			PreparedStatement pre = conn.prepareStatement(sql, PreparedStatement.RETURN_GENERATED_KEYS);
			pre.setString(1,"格锅");
			pre.setString(2,"男");
			pre.executeUpdate();
//			如何插入多条
			pre.setString(1,"格锅");
			pre.setString(2,"女");
			pre.executeUpdate();
			ResultSet resultSet=pre.getGeneratedKeys();
			if (resultSet.next()){
				resultSet.getInt(1);
			}


		} catch (SQLException e) {
			e.printStackTrace();
			conn.rollback();
		} finally {
			conn.commit();
		}
//		int count = cs.executeUpdate(sql);
//		System.out.println("count "+count);
//		关闭连接
//		cs.close();
//		conn.close();
	}
}
